<template>
  <div class="template-container">
    <a-card title="模板管理" :bordered="false">
      <!-- 搜索表单 -->
      <div class="search-header">
        <a-form
          :model="searchForm"
          layout="inline"
          class="search-form"
          @finish="handleSearch"
        >
          <a-form-item label="模板名称" name="name">
            <a-input
              v-model:value="searchForm.name"
              placeholder="请输入模板名称"
              style="width: 200px"
              allowClear
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">搜索</a-button>
            <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
          </a-form-item>
        </a-form>
        <a-button type="primary" @click="showAddModal">添加模板</a-button>
      </div>

      <!-- 模板列表 -->
      <a-table
        :columns="columns"
        :data-source="templateList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="handleView(record)">参数配置</a-button>
            <a-button type="link" @click="handleEdit(record)">编辑</a-button>
            <a-button type="link" danger @click="handleDelete(record)">删除</a-button>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加模板弹窗 -->
    <a-modal
      v-model:visible="addModalVisible"
      title="添加模板"
      @ok="handleAdd"
      @cancel="handleAddCancel"
      :confirmLoading="addLoading"
    >
      <a-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        layout="vertical"
      >
        <a-form-item label="模板名称" name="name">
          <a-input
            v-model:value="addForm.name"
            placeholder="请输入模板名称"
            allowClear
          />
        </a-form-item>
        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="addForm.description"
            placeholder="请输入模板描述"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑模板弹窗 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑模板"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
      :confirmLoading="editLoading"
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        layout="vertical"
      >
        <a-form-item label="模板名称" name="name">
          <a-input
            v-model:value="editForm.name"
            placeholder="请输入模板名称"
            allowClear
          />
        </a-form-item>
        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="editForm.description"
            placeholder="请输入模板描述"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 参数配置抽屉 -->
    <a-drawer
      title="参数配置"
      placement="right"
      :visible="drawerVisible"
      @close="handleDrawerClose"
      width="720"
    >
      <div class="transfer-container">
        <a-transfer
          :dataSource="transferData"
          :targetKeys="targetKeys"
          @change="handleTransferChange"
          :titles="['可配置属性', '已配置属性']"
          :listStyle="{
            width: '300px',
            height: '500px'
          }"
        >
          <template #render="item">
            <span>{{ item.title }}</span>
          </template>
        </a-transfer>
        <div class="transfer-footer">
          <a-button type="primary" @click="handleBindSubmit" :loading="bindLoading">确定</a-button>
          <a-button style="margin-left: 8px" @click="handleDrawerClose">取消</a-button>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { getStoreTemplate, addTemplate, delTemplate, modifyTemplate, detail, bindParam } from '@/api/template';
import { listAllStores } from '@/api/store';
import { message, Modal } from 'ant-design-vue';
import type { TablePaginationConfig } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { useStoreMsgStore } from '@/store/useStoreMsgStore';

interface Store {
  storeId: string;
  storeName: string;
}

interface Template {
  id: number;
  name: string;
  description: string;
  storeId: string;
}

interface TransferItem {
  key: string;
  title: string;
  description: string;
}

// 搜索表单
const searchForm = reactive({
  name: '',
  pageNum: 1,
  pageSize: 10
});

// 获取当前门店信息
const storeMsg = useStoreMsgStore();

// 门店列表
const storeList = ref<Store[]>([]);

// 模板列表
const templateList = ref<Template[]>([]);
const loading = ref(false);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条记录`
});

// 表格列配置
const columns = [
  {
    title: '模板ID',
    dataIndex: 'id',
    key: 'id',
    width: 100
  },
  {
    title: '模板名称',
    dataIndex: 'name',
    key: 'name',
    width: 200
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '所属门店',
    dataIndex: 'storeId',
    key: 'storeId',
    width: 200,
    customRender: ({ text }: { text: string }) => {
      const store = storeList.value.find(s => s.storeId === text);
      return store?.storeName || text;
    }
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
];

// 加载门店列表
const loadStoreList = async () => {
  try {
    const res = await listAllStores();
    if (res.data.code === 200) {
      storeList.value = res.data.data;
    } else {
      message.error(res.data.msg || '获取门店列表失败');
    }
  } catch (error) {
    console.error('获取门店列表失败:', error);
    message.error('获取门店列表失败，请稍后重试');
  }
};

// 加载模板列表
const loadTemplateList = async () => {
  loading.value = true;
  try {
    const res = await getStoreTemplate(
      storeMsg.storeId,
      searchForm.name,
      searchForm.pageNum,
      searchForm.pageSize
    );
    if (res.data.code === 200) {
      templateList.value = res.data.data.list;
      pagination.total = res.data.data.total;
    } else {
      message.error(res.data.msg || '获取模板列表失败');
    }
  } catch (error) {
    console.error('获取模板列表失败:', error);
    message.error('获取模板列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  searchForm.pageNum = 1;
  loadTemplateList();
};

// 处理重置
const handleReset = () => {
  searchForm.name = '';
  searchForm.pageNum = 1;
  loadTemplateList();
};

// 处理表格变化
const handleTableChange = (pag: TablePaginationConfig) => {
  searchForm.pageNum = pag.current || 1;
  searchForm.pageSize = pag.pageSize || 10;
  loadTemplateList();
};

// 参数配置相关
const drawerVisible = ref(false);
const currentTemplate = ref<Template | null>(null);
const transferData = ref<TransferItem[]>([]);
const targetKeys = ref<string[]>([]);
const bindLoading = ref(false);
const selectedKeys = ref<string[]>([]);
const bindDetail = ref<any[]>([]);

// 处理查看（参数配置）
const handleView = async (record: Template) => {
  currentTemplate.value = record;
  drawerVisible.value = true;
  try {
    const res = await detail(record.id);
    if (res.data.code === 200) {
      const detailData = res.data.data.bindDetail || [];
      bindDetail.value = detailData;
      
      // 处理左侧数据（可配置属性）
      const leftData: TransferItem[] = [];
      detailData.forEach((param: any) => {
        if (param.canBindValueList && param.canBindValueList.length > 0) {
          param.canBindValueList.forEach((value: any) => {
            leftData.push({
              key: `${param.id}-${value.id}`,
              title: `${param.name}-${value.value}`,
              description: value.description || ''
            });
          });
        }
      });
      
      // 处理右侧数据（已配置属性）
      const rightData: TransferItem[] = [];
      const rightKeys: string[] = [];
      detailData.forEach((param: any) => {
        if (param.haveBindValueList && param.haveBindValueList.length > 0) {
          param.haveBindValueList.forEach((value: any) => {
            const key = `${param.id}-${value.id}`;
            rightData.push({
              key,
              title: `${param.name}-${value.value}`,
              description: value.description || ''
            });
            rightKeys.push(key);
          });
        }
      });
      
      console.log('左侧数据:', leftData);
      console.log('右侧数据:', rightData);
      
      // 合并左右两侧数据
      transferData.value = [...leftData, ...rightData];
      targetKeys.value = rightKeys;
    } else {
      message.error(res.data.msg || '获取模板详情失败');
    }
  } catch (error) {
    console.error('获取模板详情失败:', error);
    message.error('获取模板详情失败，请稍后重试');
  }
};

// 处理穿梭框变化
const handleTransferChange = (newTargetKeys: string[]) => {
  targetKeys.value = newTargetKeys;
};

// 处理绑定提交
const handleBindSubmit = async () => {
  if (!currentTemplate.value) return;
  
  bindLoading.value = true;
  try {
    // 提取参数值ID列表
    const paramValueIdList = targetKeys.value.map(key => {
      const [, valueId] = key.split('-');
      return parseInt(valueId);
    });

    const res = await bindParam({
      templateId: currentTemplate.value.id,
      paramValueIdList
    });

    if (res.data.code === 200) {
      message.success('参数配置更新成功');
      drawerVisible.value = false;
    } else {
      message.error(res.data.msg || '参数配置更新失败');
    }
  } catch (error) {
    console.error('参数配置更新失败:', error);
    message.error('参数配置更新失败，请稍后重试');
  } finally {
    bindLoading.value = false;
  }
};

// 处理抽屉关闭
const handleDrawerClose = () => {
  drawerVisible.value = false;
  currentTemplate.value = null;
  transferData.value = [];
  targetKeys.value = [];
};

// 处理编辑
const handleEdit = (record: Template) => {
  editForm.id = record.id.toString();
  editForm.name = record.name;
  editForm.description = record.description;
  editModalVisible.value = true;
};

// 处理删除
const handleDelete = (record: Template) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除模板"${record.name}"吗？`,
    okText: '确认',
    cancelText: '取消',
    okButtonProps: { danger: true },
    onOk: async () => {
      try {
        const res = await delTemplate(record.id);
        if (res.data.code === 200) {
          message.success('删除成功');
          loadTemplateList();
        } else {
          message.error(res.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除模板失败:', error);
        message.error('删除失败，请稍后重试');
      }
    }
  });
};

// 添加模板相关
const addModalVisible = ref(false);
const addLoading = ref(false);
const addFormRef = ref<FormInstance>();
const addForm = reactive({
  name: '',
  description: ''
});

const addFormRules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入模板描述', trigger: 'blur' }]
};

// 显示添加弹窗
const showAddModal = () => {
  addModalVisible.value = true;
};

// 处理添加
const handleAdd = () => {
  addFormRef.value?.validate().then(async () => {
    addLoading.value = true;
    try {
      const res = await addTemplate({
        storeId: storeMsg.storeId,
        name: addForm.name,
        description: addForm.description
      });
      if (res.data.code === 200) {
        message.success('添加成功');
        addModalVisible.value = false;
        loadTemplateList();
      } else {
        message.error(res.data.msg || '添加失败');
      }
    } catch (error) {
      console.error('添加模板失败:', error);
      message.error('添加失败，请稍后重试');
    } finally {
      addLoading.value = false;
    }
  });
};

// 处理添加取消
const handleAddCancel = () => {
  addFormRef.value?.resetFields();
  addModalVisible.value = false;
};

// 编辑模板相关
const editModalVisible = ref(false);
const editLoading = ref(false);
const editFormRef = ref<FormInstance>();
const editForm = reactive({
  id: '',
  name: '',
  description: ''
});

const editFormRules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入模板描述', trigger: 'blur' }]
};

// 处理编辑提交
const handleEditSubmit = () => {
  editFormRef.value?.validate().then(async () => {
    editLoading.value = true;
    try {
      const res = await modifyTemplate({
        id: editForm.id,
        name: editForm.name,
        description: editForm.description
      });
      if (res.data.code === 200) {
        message.success('修改成功');
        editModalVisible.value = false;
        loadTemplateList();
      } else {
        message.error(res.data.msg || '修改失败');
      }
    } catch (error) {
      console.error('修改模板失败:', error);
      message.error('修改失败，请稍后重试');
    } finally {
      editLoading.value = false;
    }
  });
};

// 处理编辑取消
const handleEditCancel = () => {
  editFormRef.value?.resetFields();
  editModalVisible.value = false;
};

onMounted(() => {
  loadStoreList();
  loadTemplateList();
});
</script>

<style scoped>
.template-container {
  padding: 24px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.search-form {
  flex: 1;
  margin-right: 16px;
}

:deep(.ant-table) {
  margin-top: 16px;
}

.transfer-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.transfer-footer {
  margin-top: 16px;
  text-align: right;
  padding: 8px 0;
}

:deep(.ant-transfer-list-content-item) {
  padding: 8px !important;
  display: flex;
  align-items: center;
}

:deep(.ant-transfer-list-content-item-text) {
  margin-left: 8px;
}
</style> 